' //***************************************************************************
' // ***** Script Header *****
' //
' // Solution:  Solution Accelerator for Business Desktop Deployment
' // File:      DeployWiz_Initialization.vbs
' //
' // Purpose:   Initialize wizard panes used in the deployment wizard
' //
' // Usage:     (used by DeployWiz_Definition_ENU.xml)
' //
' // Microsoft Solution Version:  3.0.112
' // Microsoft Script Version:    3.0.112
' // Customer Build Version:	  1.0.0
' // Customer Script Version:     1.0.0
' //
' // Microsoft History:
' // 3.0.53   MTN   08/04/2006  Added comment block, product key logic
' // 3.0.100  MTN   10/31/2006  Changed to use DomainOUs
' // 3.0.108  MTN   11/09/2006  Added SMSImage filter
' // 3.0.112  MTN   11/19/2006  Added BDE initialization functions
' // 4.0.325  TJ    09/08/2006  Added warning for Image Capture workgroup 
' //							selection.
' // 4.0.362  TJ    10/16/2006  Added TS filtering to supress OSD Tasks
' //
' // Customer History:
' //
' // ***** End Header *****
' //***************************************************************************


Option Explicit

''''''''''''''''''''''''''''''''''''''''''''''''''
'  DeployRoot!
'

Dim oXMLSiteData

Function InitializeDeployRoot

	Dim oXMLDefault
	Dim oItem
	Dim oOption
   
	Set oXMLSiteData = nothing
	' Save the local DeployRoot location
	If property("LocalDeployRoot") = "" then
		oProperties("LocalDeployRoot") = property("DeployRoot")
	End if

	' Load the Site Configuration XML file.
	Set oXMLSiteData = oUtility.CreateXMLDOMObjectEx( property("DeployRoot") & "\control\LocationServer.xml" )
	If oXMLSiteData is nothing then
		RadioCT2.checked = TRUE
		SiteList.disabled = TRUE
		DisplayLocal.style.display = "none"
		'err.Raise 507,, "FATAL ERROR: Could not load XMLDOM Object."
		Exit function 
	End if
  
	If not ( oXMLSiteData.selectNodes("//servers/server") is nothing ) then
		While SiteList.options.length > 0 
			SiteList.remove 0
		Wend	
	End if 
   
	For each oItem in oXMLSiteData.selectNodes("//servers/server")
   
		Set oOption = document.createElement("OPTION")
		oOption.Value = oItem.selectSingleNode("serverid").text
		oOption.Text = oItem.selectSingleNode("friendlyname").text
		SiteList.Add oOption
   
	Next
   
	' Now attempt to get a default from a server!
	If oXMLSiteData.selectSingleNode("//servers/QueryDefault").TExt <> "" then

		Set oXMLDefault = oUtility.CreateXMLDOMObjectEx( oXMLSiteData.selectSingleNode("//servers/QueryDefault").TExt )
		If not (oXMLDefault is nothing) then
			For each oItem in oXMLDefault.selectNodes("//DefaultSites/DefaultSite")
				SiteList.Value = oItem.Text
				If SiteList.Value = oItem.Text then 
					Exit for
						End if
		 		Next
	  		End if
		Set oXMLDefault = nothing
	  
	End if
   
	DisplayValidateDeployRoot
   
End Function


'''''''''''''''''''''''''''''''''''''
'  DomainMembership
'

Function SkipDomainMembershipIfUpgrade

	SkipDomainMembershipIfUpgrade = Property("DeploymentType")<>"UPGRADE"
   
	If not SkipDomainMembershipIfUpgrade then   
		oProperties("JoinDomain") = ""	   
		oProperties("Workgroup") = ""  
	End if  

End function


Function PrePopulateDomainMembership

	' If the Domain membership credentials are blank, then pre-populate with the network share credentials.
    ' unless SkipDomainMembership is selected.
    
    
    If UCase(Property("SkipDomainMembership")) = "YES" then
		PrePopulateDomainMembership = TRUE	
		 Exit Function
    End If
    
   
	If Property("DomainAdmin") = "" and Property("DomainAdminDomain") = "" and Property("DomainAdminPassword") = "" then
		If Property("UserID") <> "" and Property("USerDomain") <> "" and Property("UserPassword") <> "" Then
	  
			oProperties("DomainAdmin") = Property("UserID")
			oProperties("DomainAdminDomain") = Property("USerDomain")
			oProperties("DomainAdminPassword") = Property("UserPassword")
	  
		End if	  
	End if
	

	PrePopulateDomainMembership = TRUE

End function


''''''''''''''''''''''''''''

Function AddItemToMachineObjectOUOpt(item)
   	Dim oOption
   
	set oOption = document.createElement("OPTION")
	oOption.Value = item
	oOption.Text = item
	MachineObjectOUOptional.Add oOption
	MachineObjectOUOptionalBtn.style.display = "inline"

End function


Function InitializeDeploymentType

	' We do not support any upgrades from Windows 2000 or from XP x64 platforms.
	DTRadio2.Disabled = Property("OSVERSION") = "2000" or (Property("ARCHITECTURE") = "X64" and Property("OSCurrentBuild") < "6000" and UCase(Property("IsServerOS")) = "FALSE")

End function 


Function InitializeDomainMembership
	Dim oLDAP, oOptOU, oItem


	' Warn user if image capture is required to select Workgroup

	If UCase(Property("SkipCapture")) = "NO" Then
		DisplayCaptureWarning.style.display = "inline"
	Else
		DisplayCaptureWarning.style.display = "none"
	End If


	If Workgroup.value <> "" then
		JDRadio2.checked = TRUE
	ElseIf JoinDomain.Value = "" then
		On Error Resume Next
		JoinDomain.value = CreateObject("ADSystemInfo").DomainShortName
		On Error Goto 0
		
		If JoinDomain.Value = "" then
			Workgroup.value = "WORKGROUP"
			JDRadio2.checked = TRUE
		Else
			JDRadio1.checked = TRUE
			' Domain.value = JoinDomain.Value
		   
			On error resume next
			' Will extract out the existing OU (if any) for the current machine.
			set oLDAP = GetObject("LDAP://" & CreateObject("ADSystemInfo").ComputerName)
			MachineObjectOU.Value = oLDAP.Get("Organizational-Unit-Name")
			On error goto 0
		   
		End if
	End if 

	
	''''''''''''''''''''''''''''''''
	'
	' Populate OU method #1 - Query ADSI 
	'
	   
	' BUGBUG - TODO
	MachineObjectOUOptionalBtn.style.display =  "none"	


	''''''''''''''''''''''''''''''''
	'
	' Populate OU method #2 - Read MachineObjectOUOptional[1...n] property
	'
	
	If MachineObjectOUOptionalBtn.style.display <> "inline" then
			oOptOU = Property("DomainOUs")	
		If isarray(oOptOU) then
		
			For each oItem in oOptOU
				AddItemToMachineObjectOUOpt oItem
			Next
			MachineObjectOUOptionalBtn.style.display = "inline"

		ElseIf oOptOU <> "" then
			AddItemToMachineObjectOUOpt oOptOU
		End if
	End if

	
	''''''''''''''''''''''''''''''''
	'
	' Populate OU method #3 - Read ...\control\DomainOUList.xml
	'
	' Example:	
	'	<?xml version="1.0" encoding="utf-8"?>
	'	<DomainOUs>
	'		<DomainOU>OU=Test1</DomainOU>
	'		<DomainOU>OU=Test2</DomainOU>
	'	</DomainOUs>
	'	   

	If MachineObjectOUOptionalBtn.style.display <> "inline" then
		on error resume next
		Set oXMLSiteData = oUtility.CreateXMLDOMObjectEx( property("DeployRoot") & "\control\DomainOUList.xml" )
		on error goto 0
		If not oXMLSiteData is nothing then
			For each oItem in oXMLSiteData.selectNodes("//DomainOUs/DomainOU")
				AddItemToMachineObjectOUOpt oItem.text
			Next
		End if
	End if

	If MachineObjectOUOptionalBtn.style.display = "inline" then	

		document.body.onMouseDown = getRef("DomainMouseDown")
		document.body.onKeyDown   = getRef("MachineObjectOUOptionalKeyPress")
		
	End if

	ValidateDomainMembership
	
End Function


Function MachineObjectOUOptionalKeyPress
	
	dim OUOpt 

	on error resume next
	set OUOpt = MachineObjectOUOptional
	on error goto 0

	If isempty(OUOpt) then
		KeyHandler
	ElseIf window.event.srcElement is MachineObjectOUOptional then
		If window.event.keycode = 13 then
		' Enter
			MachineObjectOU.value = MachineObjectOUOptional.value
			PopupBox.style.display = "none"
		
		ElseIf window.event.keycode = 27 then
			' escape
			PopupBox.style.display = "none"		
		End if
	Else
		KeyHandler
	End if

End function


Function DomainMouseDown
	If not window.event.srcElement is MachineObjectOUOptional and not window.event.srcElement is MachineObjectOUOptionalBtn then   
		PopupBox.style.display = "none"
	End if 
End function 


Function HideUnHideComboBox

	If UCase(PopupBox.style.display) <> "NONE" then
   
		HideUnhide PopupBox, FALSE
	  
		document.body.onMouseDown = ""
		document.body.onKeyDown   = getRef("KeyHandler")

	Else
   
		HideUnhide PopupBox, TRUE
		MachineObjectOUOptional.focus
	  
		document.body.onMouseDown = getRef("DomainMouseDown")
		document.body.onKeyDown   = getRef("MachineObjectOUOptionalKeyPress")
	  
	End if

End function 


Function InitializeUserDataLocation

	' We muck arround with the values, so we need to do some manual cleanup
   
	If UCase(property("UserDataLocation")) = "" then
	  
	ElseIf UCase(property("UserDataLocation")) = "AUTO" then
		AllowLocal.Checked = TRUE
		UDRadio1.click	  
		UDRadio1.value = "AUTO"
	  
	ElseIf UCase(property("UserDataLocation")) = "NONE" then
		UDRadio3.click	  
	  
	ElseIf UCase(property("UserDataLocation")) = "NETWORK" then
		AllowLocal.Checked = FALSE
		UDRadio1.click   
		UDRadio1.value = "NETWORK"
	  
	Else
		DataPath.Value = property("UserDataLocation")
		UDRadio2.click	  
	End if
   

	If property("DeploymentType") = "REPLACE" then   
   
		If UDRadio3.Checked then
			UDRadio2.Click
		End if
		UDRadio3.Disabled = TRUE  

	End if
   
	If (property("UDShare") = "" or property("UDDir") = "") and property("DeploymentType") <> "REFRESH" then
	  
		If UDRadio1.Checked then
			UDRadio2.Click 
		End if
		UDRadio1.Disabled = TRUE  
	  
	End if
   
	ValidateUserDataLocation

End function


Function InitializeUserDataRestoreLocation

	' If the user data location is AUTO or NETWORK, reset it to none for bare metal

	If UCase(Property("UserDataLocation")) = "AUTO" or UCase(Property("UserDataLocation")) = "NETWORK" then
		oProperties("UserDataLocation") = "NONE"
	End if
 

	' Make sure the right radio button is set

	If UCase(Property("UserDataLocation")) = "NONE" then
		UDRadio1.click
	Else
		StatePath.value = Property("UserDataLocation")
		UDRadio2.click
	End if

End Function


Function InitializeComputerBackupLocation

	' We muck arround with the values, so we need to do some manual cleanup
   	
	If Ucase(property("DeploymentType")) = "REPLACE" then
		oProperties("ComputerBackupLocation") = "NETWORK"
	End if 
	If UCase(property("ComputerBackupLocation")) = "" then
	  
	ElseIf UCase(property("ComputerBackupLocation")) = "AUTO" then
		AllowLocal.Checked = TRUE
		CBRadio1.click	  
	  
	ElseIf UCase(property("ComputerBackupLocation")) = "NONE" then
		CBRadio3.click	  
	  
	ElseIf UCase(property("ComputerBackupLocation")) = "NETWORK" then
		CBRadio1.Disabled = TRUE
		AllowLocal.Checked = FALSE
		CBRadio2.click	   

	Else
		DataPath.Value = property("ComputerBackupLocation")
		CBRadio2.click	  
	End if
   
	ValidateComputerBackupLocation

End function


'''''''''''''''''''''''''''''''''''''
' Filter out all elements with attribute enable = 'False' or 'hide' = 'True' along with children of that element.
'

Function RemoveNonEnabledElements( XMLFile )
	Dim oXSL, oXML 
   
	Set oXML = oUtility.CreateXMLDOMObjectEx( XMLFile)
	Set oXSL = oUtility.CreateXMLDOMObject
	Set RemoveNonEnabledElements = oUtility.CreateXMLDOMObject
   
	If not oXML is nothing then
		oXSL.loadXML "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" >" & _ 
			"	<xsl:template match=""@*|node()""><xsl:copy><xsl:apply-templates select=""@*|node()""/></xsl:copy></xsl:template>" & _ 
			"	<xsl:template match=""*[@enable = 'False' or @hide = 'True']"" />" & _ 
			"</xsl:stylesheet>"

		oXML.transformNodeToObject oXSL, RemoveNonEnabledElements
	  
		If RemoveNonEnabledElements.xml = "" then
			set RemoveNonEnabledElements = nothing		 
		End if
		
		If RemoveNonEnabledElements.documentElement.childNodes.length = 0 then
			set RemoveNonEnabledElements = nothing
		End if
	End if 

End function


'''''''''''''''''''''''''''''''''''''
'  Image List
'

Function InitializeTSList

	Dim oTSList
	Dim oTSArray
	Dim oTS
	Dim oSupportedPlatformList
	Dim oPlatform
	Dim bIsSupported
	Dim oTaskId, oTaskList, oTaskOsGuid, oOperatingSystems, oOS, sIsSms, sOSPlatform
	
	Set oTSList = RemoveNonEnabledElements( Property("DeployRoot") & "\Control\TaskSequences.xml" )	
	
	If oTSList is nothing then
		Exit function 
	End if


	' Add support for parsing supported platforms
	
	Set oTSArray = oTSList.getElementsByTagName("ts")

	For each oTS in oTSArray

		' Validate that the Operating System is not SMS.

		Set oTaskId = oTS.selectSingleNode("ID")	
		Set oTaskList = oUtility.CreateXMLDOMObjectEx( Property("DeployRoot") & "\Control\" & oTaskId.text & "\TS.xml")
		Set oTaskOsGuid = oTaskList.SelectSingleNode("//globalVarList/variable[@name='OSGUID']")
		
		If not oTaskOsGuid is Nothing then
			Set oOperatingSystems = oUtility.CreateXMLDOMObjectEx( Property("DeployRoot") & "\Control\OperatingSystems.xml" )
			Set oOS = oOperatingSystems.selectSingleNode("//os[@guid='" & oTaskOsGuid.text & "']")

			If oOS is Nothing then
				sIsSms = "False"
				sOSPlatform = "" 
				oLogging.CreateEntry "ERROR: Invalid OS GUID " & oTaskOsGuid.text & " specified for task sequence " & oTaskId.text & " specified", LogTypeError
			Else
				sIsSms = oOS.selectSingleNode("SMSImage").text	
				sOSPlatform = oOS.selectSingleNode("Platform").text
			End if		

		Else
			sIsSms = "False"
			sOSPlatform = "" 
		End if


		' Filter out based on supported platform list
	
		Set oSupportedPlatformList = oTS.getElementsByTagName("SupportedPlatform")		
		bIsSupported = True
		
		For each oPlatform in oSupportedPlatformList
			bIsSupported = oUtility.IsSupportedPlatform(oPlatform.Text)
				
			If bIsSupported = True Then
				Exit For
			End If
		Next


		' Filter unsupported and impossible choices based on the OS contained in the task sequence, regardless of
		' what the supported platform list says.

		If sOSPlatform <> "" then


			' We don't currently support cross-platform deployments in Windows PE

			If oEnv("SystemDrive") = "X:" and UCase(sOSPlatform) <> UCase(oEnvironment.Item("Architecture")) then
				bIsSupported = false
			End if


			' We can't deploy an OS if the machine isn't capable of running it

			If Instr(1, Property("CapableArchitecture"), sOSPlatform, vbTextCompare) = 0 then
				bIsSupported = false
			End if

		End if


		' Finally do the removal
			
		If bIsSupported = False or sIsSms = "True"  Then
			oTS.parentNode.removeChild oTS
		End If
	Next	  


	tasksequences.XMLDocument.LoadXML oTSList.xml
		
End Function


Function ReadyInitializeTSList
	' We muck arround with the values, so we need to do some manual cleanup

	Dim oInput, oTSList
	Dim bFound
   
	ButtonNext.Disabled = TRUE

	If not TSList.readystate = "complete" then
		Exit function	  
	End if 
   
	Set oTSList = document.getElementsByName("TSGuid")
   
	If oTSList is nothing then
		Exit function
	End if
   
	If oTSList.Length > 0 then
		bFound = FALSE
	  
		For each oInput in oTSList
			If oInput.Value <> "" and StrComp(oInput.Value,ForceAsString(oproperties("TSGuid")),vbTextCompare) = 0 then
				document.all.item(oInput.SourceIndex - 1).click
				ButtonNext.Disabled = FALSE
				bFound = TRUE
			End if
		Next	  
	  
		If not bFound and oTSList.Item(0).Value <> "" then
			' Just select the first item
			document.getElementsByName("SelectedItem").Item(0).click   
			ButtonNext.Disabled = FALSE
		End if

	End if   

	' After we extract the value from the system, clear the value (incase we go backwards).

	If ForceAsString(oProperties("TSGuid")) <> "" then
		oProperties("TSGuid") = ""
	End if

End function


Function SetTimeZoneValue
	' When the user selects a value in the TimeZoneList we must populate the hidden Text Values
	Dim TimeSplit

	TimeSplit = split( TimeZoneList.value , ";" )
	If ubound(TimeSplit) < 1 then 
	ElseIf not isNumeric(TimeSplit(0)) then
	Else
		TimeZoneName.Value = TimeSplit(1)
		TimeZone.Value = TimeSplit(0)   
	End if
	
End function 


Function TimeZone_Initialization

	Dim TimeZone, i, TimeSplit, Item, test
	
	'If either of the TimeZone Properties have been set, then select the coresponding list item.
	If Property("TimeZone") <> "" or Property("TimeZoneName") <> "" then 
		For i = 0 to TimeZoneList.Options.Length - 1
	   
			TimeSplit = split( TimeZoneList.Options(i).value , ";" )
		   
			If ubound(TimeSplit) >= 1 then
				If Property("TimeZone") <> "" then
					If IsNumeric(Property("TimeZone")) then			  
						' Check Windows XP style Name
						If CInt(Property("TimeZone")) = cint(TimeSplit(0)) then
							TimeZoneList.SelectedIndex = i
							SetTimeZoneValue
							Exit function 
						End if
					Else
						' Check Windows Vista Style Name
						If UCase(Property("TimeZone")) = UCase(TimeSplit(1)) then 
							TimeZoneList.SelectedIndex = i
							SetTimeZoneValue
							Exit function 
						End if				
					End if
				ElseIf Property("TimeZoneName") <> "" then
					' Check Windows Vista Style Name
					If UCase(Property("TimeZoneName")) = UCase(TimeSplit(1)) then 
						TimeZoneList.SelectedIndex = i
						SetTimeZoneValue
						Exit function 
					End if
				End if
			End if 
		Next
	End if
	
	' Extract out the current TimeZone			   
	For each TimeZone in objWMI.InstancesOf("Win32_TimeZone")
		Exit for ' Take the first entry and break out of loop
	Next
	
	If IsEmpty(TimeZone) then
		Exit function 
	End if
	
	'Try to match the timezone against the current Timezone Name
	For i = 0 to TimeZoneList.Options.Length - 1
   
		TimeSplit = split( TimeZoneList.Options(i).value , ";" )
	   
		If UBound(TimeSplit) >= 1 then			   
			' Compare the Description
			If UCase(TimeZoneList.Options(i).Text) = UCase(TimeZone.Description) then
				TimeZoneList.SelectedIndex = i
				SetTimeZoneValue
				Exit function
			End if
		  
			' See if there is a match in the alternate description or other Values				  
			For each test in array(TimeZone.Description,TimeZone.StandardName)
				If test <> "" then
					For each item in TimeSplit
						If Item <> "" then
				   
							If UCase(test) = UCase(Item) then
								TimeZoneList.SelectedIndex = i
								SetTimeZoneValue
								Exit function
							End if
					  
						End if						
					Next
				End if
			Next
		  
		End if 
	Next
	

	' Try to match against the closest GMT value (This *May* select an entry that is not *exact*)
	For i = 0 to TimeZoneList.Options.Length - 1
	
		test = Instr(1, TimeZone.Description," ")
		If test <> 0 then

			If left(TimeZone.Description, test) = left(TimeZoneList.Options(i).Text, test) then
				TimeZoneList.SelectedIndex = i
				SetTimeZoneValue
				Exit function
			End if
	   
		End if
	Next

End function


'''''''''''''''''''''''''''''''''''''''''''
'  Application List
'

Dim g_oApplicationList

Function IsThereAtLeastOneApplicationPresent

	Dim oTaskList
	Dim oAction

	If IsEmpty(g_oApplicationList) then		
		Set g_oApplicationList = RemoveNonEnabledElements( Property("DeployRoot") & "\Control\applications.xml" )		
	End if 

	IsThereAtLeastOneApplicationPresent = FALSE
	If not g_oApplicationList is nothing then
		If g_oApplicationList.childNodes.length > 0 Then

			IsThereAtLeastOneApplicationPresent = True
			
			' Do not display if the Task Sequence is missing a ZTIApplications.wsf step.
			Set oTaskList = oUtility.CreateXMLDOMObjectEx( oEnvironment.Item("DeployRoot") & "\Control\" & Property("TaskSequenceID") & "\TS.XML" ) 	
			If oTaskList.SelectSingleNode("//step[@type='BDD_InstallApplication']") is nothing then

				IsThereAtLeastOneApplicationPresent = FALSE
				oLogging.CreateEntry "Unable to find Task Sequence step of type BDD_InstallApplication, performing more exhaustive search...", LogTypeInfo

				For each oAction in oTaskList.SelectNodes("//action") 	
					If instr(1,oAction.XML,"ZTIApplications.wsf",vbTExtCompare) <> 0 then
						oLogging.CreateEntry "Found ZTIApplications.wsf...", LogTypeInfo
						IsThereAtLeastOneApplicationPresent = True
						exit for
					End if
				Next

			End if

		End if
	End if

End function

Function InitializeApplicationList

	If IsEmpty(g_oApplicationList) then		
		Set g_oApplicationList = RemoveNonEnabledElements( Property("DeployRoot") & "\Control\applications.xml" )		
	End if 
	
	If not g_oApplicationList is nothing then
		images.XMLDocument.LoadXML g_oApplicationList.xml
	End if 

End Function


Function ReadyInitializeApplicationList
	Dim oInput, oApplicationList, oAppItem
	
	If not ImageList.readystate = "complete" then
		Exit function	   
	End if
	
	Set oApplicationList = document.getElementsByName("Applications")
   
	If oApplicationList is nothing then
		Exit function
	ElseIf oApplicationList.Length < 1 then
		Exit function 
	End if
	
	For each oInput in oApplicationList
		If UCase(document.all.item(oInput.SourceIndex - 1).TagName) = "INPUT" then
			If oInput.Value = "" then
				document.all.item(oInput.SourceIndex - 1).Disabled = TRUE
				document.all.item(oInput.SourceIndex - 1).Style.Display = "none"
			Else
				document.all.item(oInput.SourceIndex - 1).Style.Display = "inline" 
				If not IsEmpty(Property("Applications"))then
					For each oAppItem in Property("Applications")
						If UCase(oAppItem) = UCase(oInput.Value) then			   
							document.all.item(oInput.SourceIndex - 1).checked = TRUE
							Exit for
						End if
					Next
				End if
				If not IsEmpty(Property("MandatoryApplications"))then
					For each oAppItem in Property("MandatoryApplications")
						If UCase(oAppItem) = UCase(oInput.Value) then			   
							document.all.item(oInput.SourceIndex - 1).disabled = TRUE
							document.all.item(oInput.SourceIndex - 1).checked = TRUE
							Exit for
						End if
					Next
				End if
			
			End if 
		End if

	Next

End function


Sub AppItemChange

	document.all.item(window.event.srcElement.SourceIndex + 1).Disabled = not window.event.SrcElement.checked
   
End sub


'
' Will return a dictionary object containing all Friendly Names Given a GUID as string, this funtion will search all *.xml files in the deployroot for a match.
'
Function GetFriendlyNamesofGUIDs

	Dim oFiles
	Dim oFolder
	Dim oXMLFile
	Dim oXMLNode
	Dim sName
	Dim GuidList
	
	Set GuidList = CreateObject("Scripting.Dictionary")
	GuidList.CompareMode = vbTextCompare

	Set oFolder = oFSO.GetFolder( oEnvironment.Item("DeployRoot") & "\control" )
	If oFolder is nothing then
		oLogging.CreateEntry oUtility.ScriptName & " Unable to find DeployRoot!", LogTypeError
		Exit function 
	End if  

	For each oFiles in oFolder.Files

		If UCase(right(oFIles.Name, 4)) = ".XML" then
			Set oXMLFile = oUtility.CreateXMLDOMObjectEx( oFiles.Path )
			If not oXMLFile is nothing then
			
				for each oXMLNode in oXMLFile.selectNodes("//*/*[@guid]")

					if not oXMLNode.selectSingleNode("./Name") is nothing then
						sName = oXMLNode.selectSingleNode("./Name").Text
			
						if not oXMLNode.selectSingleNode("./Language") is nothing then
							if oXMLNode.selectSingleNode("./Language").Text <> "" then
								sName = sName & " ( " & oXMLNode.selectSingleNode("./Language").Text & " )"
							end if
						end if 
						
						if not oXMLNode.Attributes.getNamedItem("guid") is nothing then
							if oXMLNode.Attributes.getNamedItem("guid").value <> "" and sName <> "" then
								if not GuidList.Exists(oXMLNode.Attributes.getNamedItem("guid").value) then
									GuidList.Add oXMLNode.Attributes.getNamedItem("guid").value, sName
								end if
							end if
						end if
					end if

				next

			End if
		End if 
		
	Next

	set GetFriendlyNamesofGUIDs = GuidList
End function 


Function PrepareFinalScreen

    Dim GuidList
	Dim p, i, item, Buffer
    
    set GuidList = GetFriendlyNamesofGUIDs

	Dim re, Match	
	
	For each p in oProperties.Keys
	
		If IsObject(oProperties(p)) or IsArray(oProperties(p)) then
			i = 1
			For each item in oProperties(p)
				AddToList Buffer, p & i &  " = """ & item & """", vbNewLine
				i = i + 1 
		   next 
	   ElseIf Instr(1, p, "Password" , vbTextCompare ) <> 0 then
		   AddToList Buffer, p & " = ""***********""", vbNewLine
	   else
		   AddToList Buffer, p & " = """ & oProperties(p) & """", vbNewLine
	   end if
	Next

	'
	' Given a text string containing GUID ID's of configuration entries on the deployment share
	'   This function will search/replace all GUID's within the text blob.
	'
	Set re = new regexp
	re.IgnoreCase = True
	re.Global = True
	re.Pattern = "\{[A-F0-9]{8}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{12}\}"
	
	On error resume next
	Do while re.Test( Buffer ) 
		For each Match in re.execute(Buffer)
			Buffer = mid(Buffer,1,Match.FirstIndex) & _
				GuidList.Item(Match.Value) & _
				mid(Buffer,Match.FirstIndex+match.Length+1)
			Exit for
		Next
	Loop
	On error goto 0
	
	optionalWindow1.InnerText = Buffer
	
End function 


Function InitializeCapture

	ComputerBackupLocation.value = Property("DeployRoot") & "\Captures"
	BackupFile.value = Property("TaskSequenceID") & ".wim"

End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim  g_oXMLPackageList

Function oXMLPackageList

	If IsEmpty(g_oXMLPackageList) then
		Set g_oXMLPackageList = RemoveNonEnabledElements ( property("DeployRoot") & "\control\Packages.xml" )
	End if 
	Set oXMLPackageList = g_oXMLPackageList
	
End function


dim g_oXMLLanguageList

Function oXMLLanguageList

	If IsEmpty(g_oXMLLanguageList) then
		Set g_oXMLLanguageList = oUtility.CreateXMLDOMObjectEx( property("DeployRoot") & "\scripts\ListOfLanguages.xml" )
		If g_oXMLLanguageList is nothing then

			Set g_oXMLLanguageList = oUtility.CreateXMLDOMObjectEx( "ListOfLanguages.xml" )
			If g_oXMLLanguageList is nothing then
				FatalError "Unable to Create ListOfLanguages.xml" 
				Exit function 
			End if 

		End if 
	End if 
	Set oXMLLanguageList = g_oXMLLanguageList

End function

dim g_oPackageGroup

Function oPackageGroups
	If isempty(g_oPackageGroup) then
		set g_oPackageGroup = oUtility.GetWhiteListOfGUIDsFromGroup ("PackageGroups.xml", "PackageGroup")
	End if
	set oPackageGroups = g_oPackageGroup
End function

''''''''''''''''''''''''''''''''''''''

Function ConstructLPQuery ( isLangPack )
	Dim pa
	Dim isServer
	Dim isVistaSP1
   
	pa = oEnvironment.Item("ImageProcessor") 
	If UCase(pa) = "X64" then
		pa = "amd64"
	End if 
	
	isServer = inStr(1,oEnvironment.Item("ImageFlags"),"SERVER",vbTextCompare) <> 0
	isVistaSP1 = left(oEnvironment.Item("ImageBuild"),8) = "6.0.6001"

	If not isLangPack then
		ConstructLPQuery = "//packages/package[Type != 'LanguagePack' and ProcessorArchitecture = '" & pa &  "' and " & _ 
			" (ProductVersion = '" & oEnvironment.Item("ImageBuild") & "' or ProductVersion = '') ]"
	elseif isServer then
		ConstructLPQuery = "//packages/package[Type = 'LanguagePack' and ProcessorArchitecture = '" & pa &  "' and " & _ 
			" (ProductVersion = '" & oEnvironment.Item("ImageBuild") & "' or ProductVersion = '') and (Name = 'Microsoft-Windows-Server-LanguagePack-Package')]"
	ElseIf isVistaSP1 Then
		ConstructLPQuery = "//packages/package[Type = 'LanguagePack' and ProcessorArchitecture = '" & pa &  "' and " & _ 
			" (Keyword = 'SP1 Language Pack') and (Name = 'Microsoft-Windows-Client-LanguagePack-Package')]"
	Else
		ConstructLPQuery = "//packages/package[Type = 'LanguagePack' and ProcessorArchitecture = '" & pa &  "' and " & _ 
			" (Keyword != 'SP1 Language Pack') and (Name = 'Microsoft-Windows-Client-LanguagePack-Package') and " & _ 
			" (ProductVersion = '" & oEnvironment.Item("ImageBuild") & "' or ProductVersion = '') ]"
	End if 
	

End function 


Function CanDisplayPackageDialogBox 

	Dim LanguagePackCount
	Dim PackageGroupCount
	Dim oItem
	Dim LocalLanguage
	Dim KeyboardID
	Dim sGuid

	PackageGroupCount = 0
	LanguagePackCount = 0

	On error resume next
		LanguagePackCount = oXMLPackageList.selectNodes(ConstructLPQuery(TRUE)).length
		PackageGroupCount = oPackageGroups.Count
	On error goto 0
   
	CanDisplayPackageDialogBox = FALSE
	If LanguagePackCount = 0 then
		exit function
	End if 

	If PackageGroupCount <> 0 then
		For each oItem in oXMLPackageList.selectNodes(ConstructLPQuery(TRUE))
			If not oItem.Attributes.getNamedItem("guid") is nothing then
				sGuid = oItem.Attributes.getNamedItem("guid").text

				If oPackageGroups.exists(sGuid) then
					oLogging.CreateEntry vbTab & "1  Package " & sGuid & " Found valid Package Group: " & oPackageGroups.Item(sGuid), LogTypeInfo
					CanDisplayPackageDialogBox = TRUE
					exit for
				Else
					oLogging.CreateEntry vbTab & "1  Package " & sGuid & " did not match any valid Package Group ", LogTypeInfo
				End if 

			End if
		next
	Else
		oLogging.CreateEntry "Display all packages...", LogTypeInfo
		CanDisplayPackageDialogBox = TRUE
	End if
	
	If oEnvironment.Item("DeploymentType") = "UPGRADE" and not IsInstallationUltimateEnterprise and CanDisplayPackageDialogBox = TRUE then
		LocalLanguage = GetParentLanguageFromLocale(GetDefaultInstallationLanguageString)

		'If this is an upgrade, then skip if the current Language is equal to the language of the OS Selected.
		For each oItem in oEnvironment.ListItem("ImageLanguage").Keys
			If oItem <> "" then
				If GetParentLanguageFromLocale(oItem) = LocalLanguage then
					CanDisplayPackageDialogBox = FALSE	
					Exit function
					' No need to set USERLOCAL and KEYBOARDLOCALE, OS will handle properly.
				End if
			End if
		Next


		' If the current language is available as a package, then auto-select package
		For each oItem in oXMLPackageList.selectNodes(ConstructLPQuery(TRUE) & "/Language") 
			If GetParentLanguageFromLocale(oItem.TExt) = LocalLanguage then
				If oEnvironment.Item("LanguagePacks1") = "" then
					oEnvironment.Item("LanguagePacks1") = oItem.ParentNode.Attributes.getNamedItem("guid").value
					CanDisplayPackageDialogBox = FALSE
					Exit for
				End if 
			End if
		Next 
	   
	End if 

End function 


Function LanguagePack_Initialization

	Dim oItem
	Dim sContstructXML 
	Dim oLang
	Dim Done
	Dim oTmpDefault
	Dim sGuid
   
	For each oItem in oXMLPackageList.selectNodes (ConstructLPQuery(TRUE))
		
		If not oItem.Attributes.getNamedItem("guid") is nothing then
			sGuid = oItem.Attributes.getNamedItem("guid").text
			If oPackageGroups.count = 0 or oPackageGroups.exists(sGuid) then
				If oPackageGroups.count <> 0 then
					oLogging.CreateEntry vbTab & "2  Package " & sGuid & " Found valid Package Group: " & oPackageGroups.Item(sGuid), LogTypeInfo
				End if

				Set oLang = oItem.SelectSingleNode("./Language")
				If not oLang is nothing then	   
					If Instr(1, join(oEnvironment.ListItem("ImageLanguage").Keys," "), trim(oLang.text), vbTextCompare ) = 0 then
						sContstructXML = sContstructXML & oItem.xml
					Else
						sContstructXML = "<package guid='DEFAULT'><Language>" & oLang.text &  "</Language><ProductName>Not Used</ProductName>" & _ 
							"<ExtraInfo><![CDATA[ <span style='font-weight: bolder;'>( Default )</span> ]]></ExtraInfo></package>" & sContstructXML 
					End if		   
					Done = Done & vbTab & oLang.Text
				Else
					sContstructXML = sContstructXML & oItem.xml
				End if

			Else
				oLogging.CreateEntry vbTab & "2  Package " & sGuid & " did not match any valid Package Group ", LogTypeInfo
			End if 
		End if


	Next
   
	For each oItem in oEnvironment.ListItem("ImageLanguage").Keys
		If Instr(1, Done, oItem, vbTextCompare ) = 0 then
			' Prefix the default Language 
			sContstructXML = "<package guid='DEFAULT'><Language>" & oItem &  "</Language><ProductName>Not Used</ProductName>" & _ 
				"<ExtraInfo><![CDATA[ <span style='font-weight: bolder;'>( Default )</span> ]]></ExtraInfo></package>" & sContstructXML 
		End if
	Next
   
	packages.XMLDocument.LoadXML "<packages>" & sContstructXML & "</packages>"
   
End function


Function MarkupLocaleField ( LocaleName, TargetField1, TargetField2 )
	' Given a Language Name (LocaleName), place the Language type into the target HTML element.
	Dim oLang, width

	width = 99   
	For each oLang in oXMLLanguageList.selectNodes("//LOCALEDATA/LOCALE/SISO639LANGNAME")
		If Instr(1,LocaleName,oLang.Text & "-", vbTextCompare) = 1 and len(oLang.Text) < width then

			width = len(oLang.Text)		  
			TargetField1.InnerText = unescape(replace(oLang.ParentNode.selectSingleNode(TargetField1.DataFld).TExt ,"\x","%u"))
			TargetField2.InnerText = unescape(replace(oLang.ParentNode.selectSingleNode(TargetField2.DataFld).TExt,"\x","%u"))

		End if
	Next 
   
End function


Function ReadyInitializePackageList

	Dim oPackageList, oPackage, oPackItem, isUltimate, hasBeenChecked

	If not ImageList.readystate = "complete" then
		Exit function	   
	End if
	
	Set oPackageList = document.getElementsByName("LanguagePacks")
   
	If oPackageList is nothing then
		Exit function
	ElseIf oPackageList.Length < 1 then
		Exit function 
	End if
	
	hasBeenChecked = empty
	
	for each oPackage in oPackageList

		If UCase(document.all.item(oPackage.SourceIndex +4).TagName) = "LABEL" then
			If UCase(document.all.item(oPackage.SourceIndex +2).TagName) = "SPAN" then
				If UCase(document.all.item(oPackage.SourceIndex +5).TagName) = "SPAN" then
					If UCase(document.all.item(oPackage.SourceIndex +4).DataFld) = "LANGUAGE" then

						MarkupLocaleField document.all.item(oPackage.SourceIndex +4).InnerText, _
							document.all.item(oPackage.SourceIndex +2),  _
							document.all.item(oPackage.SourceIndex +5)

					End if
				End if
			End if
		End if

		If oPackage.Value = "DEFAULT" then
			If UCase(document.all.item(oPackage.SourceIndex - 1).Type) = "CHECKBOX" then
				 document.all.item(oPackage.SourceIndex - 1).Disabled = TRUE
				 document.all.item(oPackage.SourceIndex - 1).checked = TRUE
			ElseIf IsEmpty(hasBeenChecked) then
				 document.all.item(oPackage.SourceIndex - 1).checked = TRUE
				 hasBeenChecked = TRUE
			End if
		Else
			If not IsEmpty(Property("LanguagePacks"))then
				For each oPackItem in property("LanguagePacks")
					If UCase(oPackItem) = UCase(oPackage.Value) then			   
						document.all.item(oPackage.SourceIndex - 1).checked = TRUE
						Exit for
					End if
				Next
			End if			
		 End if 
		 
	Next
	
	LanguagePack_Validation
	
End function


Function PackageItemChange

   document.all.item(window.event.srcElement.SourceIndex + 1).Disabled = not window.event.SrcElement.checked

end function


function AddLocale( LocaleToAdd, isKeyboardOnly, thisLocale ) 

	Dim oLang, oOption1, oOption2, sLangToAdd 
	
	sLangToAdd = GetParentLanguageFromLocale(LocaleToAdd) 

	For each oLang in oXMLLanguageList.selectNodes("//LOCALEDATA/LOCALE[SISO639LANGNAME = '" & sLangToAdd & "']")

		If not oLang.selectSingleNode("SPARENT") is nothing then
			Set oOption1 = document.createElement("OPTION")
		  
			oOption1.Text = unescape(replace( oLang.selectSingleNode("SNATIVEDISPLAYNAME").Text & _ 
				"     -     " & oLang.selectSingleNode("SENGDISPLAYNAME").Text  ,"\x","%u"))
			oOption1.Value = oLang.selectSingleNode("IDEFAULTLANGUAGE").Text & ":0000" & oLang.selectSingleNode("IDEFAULTLANGUAGE").Text		  
			KeyboardLocale.add oOption1
			If Property("KeyboardLocale") <> "" then
				If LCase(Property("KeyboardLocale")) = LCase(oOption1.Value) then
					oOption1.Selected = true
				End If
			ElseIf UCase(oLang.selectSingleNode("SNAME").Text) = UCase(thisLocale) then
				oOption1.selected = TRUE
			End if

			If not isKeyboardOnly then
				Set oOption2 = document.createElement("OPTION")
				oOption2.Text = oOption1.Text
				oOption2.Value = oLang.selectSingleNode("SNAME").Text & "," & LocaleToAdd
				UserLocaleAndLang.add oOption2
				If Property("UserLocale") <> "" then
					If LCase(Property("UserLocale")) = LCase(oLang.selectSingleNode("SNAME").Text) then
						oOption2.selected = true
					End if
				Else
					oOption2.selected = oOption1.selected
				End if
			End if

		End if 

	Next

End function 


Function Locale_Initialization

	Dim oItem, aLangPack, FoundLocale, AddDefault, thisLocale
	Dim AllreadyAddedLanguages
   
	thisLocale = GetDefaultInstallationLocaleString
	If IsEmpty(thisLocale) then 
		thisLocale = "en-US" ' WinPE *may* not have the locale defined
	End if
   
	' Add the Locales for langauges allready installed on the image.
	AllreadyAddedLanguages = ""
	For each oItem in oEnvironment.ListItem("ImageLanguage").Keys
		If oItem <> "" then
			AddLocale oItem, FALSE, thisLocale
			AllreadyAddedLanguages = AllreadyAddedLanguages & vbTab & oItem
		End if 
	Next
   
	If AllreadyAddedLanguages = "" then
		' Add en-us just to be sure!
		AddLocale "en-us", FALSE, thisLocale
		AllreadyAddedLanguages = "en-us"
	end if 
   
	aLangPack = property("LanguagePacks")   
	If isArray(aLangPack) then
		For each oItem in aLangPack 

			FoundLocale = "" 
			If oItem = "DEFAULT" then
				' Skip...		   
			ElseIf not oXMLPackageList is nothing then
				FoundLocale = oXMLPackageList.selectSingleNode("//packages/package[@ guid='" & oItem & "']/Language").text
			End if
		 
			If FoundLocale <> "" and Instr(1,AllreadyAddedLanguages, FoundLocale, vbTextCompare ) = 0 then
				AddLocale FoundLocale, FALSE, thisLocale
			End if
  
		Next   
	End if 
   
	PopulateElements

End function


''''''''''''''''''''''''''''''''

Function GetDefaultInstallationLocaleString 

	Dim HexLocale, oItem


	' First see if a UserLocal value was specified

	If Property("UserLocale") <> "" then

		Set oItem = oXMLLanguageList.SelectSingleNode("//LOCALEDATA/LOCALE[@ID = '" & lcase(Property("UserLocale")) & "']/SNAME")
   
		If not oItem is nothing then
			GetDefaultInstallationLocaleString = oItem.Text
			Exit Function
		End if

	End if


	' No, so get the default locale 

	HexLocale = hex(GetLocale)
	While len(HexLocale) < 4 
		HexLocale = "0" & HexLocale
	Wend   
   
	Set oItem = oXMLLanguageList.SelectSingleNode("//LOCALEDATA/LOCALE[@ID = '" & lcase(HexLocale) & "']/SNAME")
   
	If not oItem is nothing then
		GetDefaultInstallationLocaleString = oItem.Text
	End if


End function 


Function GetDefaultInstallationLanguageString

	GetDefaultInstallationLanguageString = GetParentLanguageFromLocale(GetDefaultInstallationLocaleString)

End function


Function GetParentLanguageFromLocale( Locale)
	Dim oLocale

	For each oLocale in oXMLLanguageList.selectNodes("//LOCALEDATA/LOCALE/SNAME")
	
		If UCase(Locale) = UCase(oLocale.text) then
			GetParentLanguageFromLocale = oLocale.ParentNode.selectSingleNode("SISO639LANGNAME").TExt
			Exit for
		End if 
	   
	Next

End function 

''''''''''''''''''''''''''''''''

Function IsInstallationUltimateEnterprise

	If UCase(oEnvironment.Item("ImageFlags")) = "ULTIMATE" then
		IsInstallationUltimateEnterprise = TRUE
	ElseIf UCase(oEnvironment.Item("ImageFlags")) = "ENTERPRISE" then
		IsInstallationUltimateEnterprise = TRUE
	ElseIf Instr(1, oEnvironment.Item("ImageFlags"), "SERVER", 1) > 0 then
		IsInstallationUltimateEnterprise = TRUE
	Else
		IsInstallationUltimateEnterprise = FALSE
	End if 

End function 


Function InitializeProductKey

	' See if we can retrieve the product key from the configuration file

	' TODO: Add this logic.


	' Figure out how to initialize the pane.

	If Property("ProductKey") <> "" or Left(Property("ImageBuild"), 1) < "6" then
		locProductKey.disabled = false
		locProductKey.value = Property("ProductKey")
		ProductKey.value = locProductKey.value
		If Left(Property("ImageBuild"), 1) >= "6" then
			PKRadio3.click
			locOverrideProductKey.disabled = true
			OverrideProductKey.value = ""
		End if
	ElseIf Property("OverrideProductKey") <> "" then
		PKRadio2.click
		locOverrideProductKey.disabled = false
		locProductKey.disabled = true
		locOverrideProductKey.value = Property("OverrideProductKey")
		OverrideProductKey.value = locOverrideProductKey.value
		ProductKey.value = ""
	Else
		PKRadio1.click
		locOverrideProductKey.disabled = true
		locProductKey.disabled = true
		ProductKey.value = ""
		OverrideProductKey.value = ""
	End if

End Function


Function InitializeBDE

	Select Case Property("BdeInstall")
	Case "TPM"
		BdeRadio2.checked = true
		BdeModeRadio1.checked = true
	Case "TPMKey"
		BdeRadio2.checked = true
		BdeModeRadio2.checked = true
	Case "Key"
		BdeRadio2.checked = true
		BdeModeRadio3.checked = true
	Case "TPMPin"
		BdeRadio2.checked = true
		BdeModeRadio4.checked = true		
	Case Else
		BdeRadio1.Checked = true
	End Select
	
	BdeInstallSuppress.value = "YES"
End Function


Function InitializeBDEDetails
	
End Function
